<template>
  <div class="index-page">
    <main-header
      :nowdept="oper.c_login_dept_name"
      :nowdept-code="oper.c_login_dept_code" :nowuser="oper.c_oper_name"
      :nowdate="nowdate" :editpwd="editPassWD" :logout="logoutsys"
      :click-user="clickUser" :depts="oper.c_oper_depts"
      :clear-cache="clearCacheSys"
    >
      <!-- <template slot="notify">
        <sys-msg />
      </template> -->
    </main-header>
    <!-- <MainHeader
      v-if="publicShow"
      ref="header"
      :nowdept="oper.c_login_dept_name || ''"
      :nowdept-code="oper.c_login_dept_code"
      :nowuser="oper.c_oper_name"
      :nowdate="nowdate"
      :editpwd="editPassWD"
      :logout="logoutsys"
      :clear-cache="clearCacheSys"
      :click-user="clickUser"
      :depts="oper.c_oper_depts || []"
    >
      <template slot="notify">
        <sys-msg />
      </template>
    </MainHeader> -->
    <MainNav
      ref="mainNav" :menus-data="menusData" :flat-menus="flatMenus"
      :dialog-visible.sync="dialogVisible"
    />
    <el-breadcrumb v-if="$store.state.mainVuex.breadcrumb.length > 1" separator="/" class="hs-breadcrumb container fwidth">
      <el-breadcrumb-item v-for="item in $store.state.mainVuex.breadcrumb" :key="item.name">
        {{ item.cnName }}
      </el-breadcrumb-item>
    </el-breadcrumb>
    <!-- <el-tabs
      v-model="$store.state.mainVuex.tabName"
      v-loading="$store.state.mainVuex.frameLoading"
      style="flex: 1;"
      class="portal-tabs"
      @tab-remove="removeTab"
      @tab-click="tabClick"
    >
      <el-tab-pane
        v-for="(item, index) in $store.state.mainVuex.frameTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
        :closable="index >= 0"
      >
         <div v-if="item.frameNetStatus404" class="frame404">
          <img src="static/img/404.svg" alt srcset>
          抱歉找不到页面，404页面
        </div>
        <div v-if="index === 0" style="padding: 10px 14px;">
          <keep-alive>
            <router-view />
          </keep-alive>
        </div>
         <iframe
          v-else-if="!item.frameNetStatus404 && index !== 0" :id="item.id" :src="item.url"
          frameborder="0" width="100%" height="100%"
        />
      </el-tab-pane>
    </el-tabs> -->

    <el-dialog
      title="菜单自定义排序" :visible.sync="dialogVisible" width="700px"
      :before-close="handleClose"
    >
      <div class="dialog-body-wrap">
        <div class="drag-tip">
          拖动标签进行拖拽
        </div>
        <draggable
          v-model="menusData" group="people" @start="drag = true"
          @end="drag = false" @update="menuChange"
        >
          <div v-for="element in menusData" :key="element.code" class="drag-item">
            {{ element.label }}
          </div>
        </draggable>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <transition>
      <keep-alive include="SalesPerson,SalesPersonAdd">
        <router-view v-if="$store.state.mainVuex.frameTabs.length > 0" />
        <router-view v-if="$route.name && $store.state.mainVuex.frameTabs.length==0" />
      </keep-alive>
    </transition>
    <PwdReset :dialog-visible="passwordDialog" :as="args" @close="close" />
  </div>
</template>
<script>
import { cacheUtil, util } from 'utils/util'; // 缓存工具类
import { Date2String, Date2Week, isAuthorizedUrl } from 'utils/funcs';
// import SysMsg from 'src/special-components/sys-msg/sys-msg.vue';
import PwdReset from '@/modules/exportUm/reset/reset.vue';
// import { getMessage, deleteMsg } from 'src/api/home';
// import { logout } from 'src/api/login';
import { getMenu, logout } from 'src/api/user';
import MainHeader from 'src/special-components/main-header/';
import MainNav from 'src/special-components/main-nav';
import draggable from 'vuedraggable';
import { base64ToString, stringToBase64 } from 'src/utils/codeChange';
import toPage from 'src/mixins/toPage';
import { sessionCache, localCache, clear } from 'src/store/cache-util.js';
import { URLCONFIG } from '../../constant/constant';
import { isNull } from '@/modules/index/src/common/tools';
import { post } from 'utils/util';
export default {
  components: {
    MainHeader,
    MainNav,
    // SysMsg,
    draggable,
		PwdReset
  },
  mixins: [toPage],
  data() {
    return {
      frameLoading: false,
      dialogVisible: false,
      passwordDialog: false,
      origin: window.location.origin,
      isMounted: false,
      msgCount: 0,
      msgExist: 0,
      msgData: [],
      oper: {
        c_oper_name: '',
        c_oper_code: '',
        c_login_dept_code: '',
        c_login_dept_name: '',
        c_oper_depts: []
      },
      nowdate: '',
      menusData: [], // 首页一级菜单数组
      subMenuData: [],
      publicShow: false,
      loading: false,
      flatMenus: [], // 二级菜单录入数组,
      tabName: '', // 路由名称
			args: {}
    };
  },
  created() {
    // 一级菜单需求数组
    this.loadShortcut();
    this.changeTab();
    const date = new Date();
    this.nowdate = Date2String(date, 'yyyy-MM-dd') + ' ' + Date2Week(date);
    this.setOper();
    // this.fetchMes();
  },
  mounted() {
		// 检测浏览器路由改变页面不刷新问题,hash模式的工作原理是hashchange事件
		window.addEventListener('hashchange', () => {
			const currentPath = window.location.hash.slice(1);
			if (this.$route.path !== currentPath) {
				this.$router.push(currentPath);
			}
		}, false);
		const id = this.getUrlParam('id');
    let token = ''; let userId = ''; let from = '';
    if (!id) {
      const oper = JSON.parse(cacheUtil.getCookies('oper'));
      from = this.getUrlParam('from') || '';
      if (oper) {
        userId = oper.c_oper_code || '';
      }
      token = cacheUtil.getCookies('Authorization') || '';
    }
		this.args = {
			ID: id,
			UserId: userId,
			Token: token,
			From: from
		};
		this.pwdPolicy(userId);
	},
  updated() {
    this.changeTab();
  },
  methods: {
		pwdPolicy(userId) {
			post(
				SERVICE_URL + '/password_notify/expired_notify',
				{
					oper: userId
				},
				(res) => {
					if (res.status === 'S' && res.errorCode === '0') {
						console.log('res.data.data.flag', res.data.data.flag);
						if (isNull(res.data.data.flag)) return;
						if (res.data.data.flag === '2') {
							this.$message.warning({ message: res.data.data.msg, duration: 5000 });
							// this.$message.warning('密码安全级别低，请及时在菜单右上角修改密码!');
						} else if (res.data.data.flag === '1') {
							this.passwordDialog = true;
						}
						this.isLoginLoading = false;
						cacheUtil.setCookies('res', JSON.stringify(res));
						cacheUtil.setCookies('pwdPolicy', JSON.stringify(res.data.data.flag));
						console.log('res', res);
						}
				},
				(err) => {
					this.isLoginLoading = false;
					this.$message.error(err.message);
				}
			);
		},
		close() {
			console.log('emit-close');
			this.passwordDialog = false;
		},
		getUrlParam(name) {
			const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
			const str = window.location.search;
			let r = '';
			if (str.substring(0, 4) === '?id=') {
				r = str.substr(1).match(reg);
			} else {
				r = decodeURIComponent(window.atob(str.substr(1))).match(reg);
			}
			if (r != null) return unescape(r[2]); return null;
		},
    changeTab() {
      const pathArray = this.$route.name;
      const storeArray = this.$store.state.mainVuex.frameTabs;
      storeArray.forEach(item => {
        item.path = item.url.split('/').pop();
      });
      // tabName = storeArray[storeArray.length - 1].path;
    },
    logoutsys(e) {
      const logoutUrl = SERVICE_URL + '/auth/logout';
      logout({
        data: cacheUtil.getSessionOper()
      })
        .then(res => {
          /* cacheUtil.setToken(null); //放到sessionCache中
                cacheUtil.setSessionOper(null); */
          cacheUtil.clearCookie();
          window.location.href = './login.html';
        })
        .catch(error => {
          cacheUtil.clearCookie();
          window.location.href = './login.html';
          console.log('错误', error);
        });
    },
    // 将菜单数组转化为一维数组
    flatMenusData(srcArr) {
      for (let i = 0; i < srcArr.length; i++) {
        const item = srcArr[i];
        if (typeof item === 'undefined') break;
        this.flatMenus.push({
          code: item.code,
          label: item.label,
          sysUrl: item.sysUrl,
          url: item.url
        });

        if (item.subMenu.length > 0) {
          this.flatMenusData(item.subMenu);
        }
      }
    },
    // 标签页点击事件
    tabClick(tabObject) {
      const tabIndex = tabObject.index * 1;
      const { frameTabs } = this.$store.state.mainVuex;
      const newFrametas = Object.assign({}, frameTabs);
      const url = newFrametas[tabIndex].url.split('/').pop();
      // 设置面包屑导航
      const breadcrumbItem = {
        label: frameTabs[tabIndex].title,
        code: frameTabs[tabIndex].code,
        name: frameTabs[tabIndex].name,
        sysUrl: frameTabs[tabIndex].url
      };
      this.setBreadCrumdByMenu(breadcrumbItem);
      this.$router.push({ name: url });
    },
    removeTab(targetName) {
      // 删除一个tab表格默认要展示最后一个数组的元素
      // router-view也需要更新
      this.$nextTick(() => {
        setTimeout(() => {
          const triggerWord = this.$store.state.mainVuex.frameTabs;
          if (triggerWord.length === 0) { return; } else {
          const str = window.location.href;
          window.location.hash = triggerWord[triggerWord.length - 1].path;
          this.$router.push({ name: triggerWord[triggerWord.length - 1].path });
          }
        });
      }, 1000);
      const { frameTabs, tabName } = this.$store.state.mainVuex;
      let activeName = tabName;
      if (activeName === targetName) {
        frameTabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            const nextTab = frameTabs[index + 1] || frameTabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }

      this.$store.dispatch('setFrameTabsName', activeName);
      const tabs = frameTabs.filter(tab => tab.name !== targetName);
      this.$store.dispatch('setFrameTabs', tabs);

      // 设置面包屑导航
      const breadcrumbItem = frameTabs.filter(item => item.name === activeName)[0];
      this.setBreadCrumdByMenu({
        label: breadcrumbItem.title,
        code: breadcrumbItem.code,
        name: breadcrumbItem.name,
        sysUrl: breadcrumbItem.url
      });
    },
    menuChange() {
      const { menusData } = this;
      const localMenus = menusData.map(item => item.label);
      localStorage.setItem('menusData', localMenus.join(','));
    },
    showEditMenu() {
      this.dialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
    },
    // 设置子公司
    setOper() {
      const oper = JSON.parse(decodeURIComponent(cacheUtil.getCookies('oper')));
      this.oper = oper;
    },

    // 获取用户子系统菜单
    // fetchMenu(params) {
    //   getMenu(params).then(res => {
    //     this.menusData = res.data || [];
    //   });
    // },
    linkClick(item) {
    },
    moreClick(link) {
    },
    // 获取消息列表
    fetchMes() {
      getMessage({}).then(res => {
        this.msgExist = res.total;
        this.msgCount = res.total;
        if (res.model && res.model.list.length > 0) {
          this.msgData = res.model.list;
        } else {
          this.msgData = [];
        }
      });
    },
    editPassWD(e) {
    },
    clearCacheSys() {
      // 清除缓存
      clear(localCache);
      clear(sessionCache);
      if (window.localStorage.length <= 0 && window.sessionStorage.length <= 0) {
        this.$message.success({ message: '缓存清除成功', duration: 1000 });
      } else {
				this.$message.error({ message: '缓存清除失败', duration: 1000 });
      }
    },
    clickUser(e) {
      // this.$refs.header.drawer = true;
      this.$refs.header.query(util.getOper().c_oper_code);
    },
    // 加载用户快捷菜单
    loadShortcut() {
      const _this = this;
      const array1 = URLCONFIG;
      getMenu(
        {},
        res => {
          const data = res.data;
          if (res.status === 'S' && data.data && data.data.length > 0) {
            const list = _this.sortMenus(data.data);
            // menuData就是吧code等于140过滤出来
            _this.menusData = list.filter(t => {
              return t.code === '140';
            });
            _this.menusData = _this.menusData[0].subMenu;
            _this.menusData.forEach((item, index, array) => {
              item.sysUrl += array1[index];
            });
            this.flatMenusData(_this.menusData);
          }
          // _this.publicShow = true;
        },
        () => {
          // _this.publicShow = true;
        }
      );
    },
    /**
     * 对菜单进行排序
     * @srcData 菜单数据源
     */
    sortMenus(srcData) {
      const hisMenusData = localStorage.getItem('menusData');
      const menusData = (!!hisMenusData && hisMenusData.split(',')) || [];
      let tempData = [];
      const noContainArr = [];
      tempData.length = srcData.length;
      if (!!menusData && menusData.length > 0) {
        srcData.forEach(element => {
          if (menusData.includes(element.label)) {
            const sortIndex = menusData.indexOf(element.label);
            tempData[sortIndex] = element;
          } else {
            noContainArr.push(element);
          }
        });
        tempData = tempData.concat(noContainArr);
        return tempData;
      }
      return srcData;
    },
    updateShortcut(type, shortcut) {
      if (type === 'create') {
        let shortMenu = null;
        if (this.menusData && this.menusData.length > 0) {
          this.menusData[this.menusData.length - 1].label === '我的快捷入口';
          shortMenu = this.menusData[this.menusData.length - 1];
        }
        if (!shortMenu) {
          shortMenu = {
            label: '我的快捷入口',
            subMenu: [],
            icon: '',
            url: ''
          };
          this.menusData.push(shortMenu);
        }

        const item = {
          icon: '',
          url: ''
        };
        item.label = shortcut.c_page_name;
        item.componentName = shortcut.c_comp_name;
        item.code = shortcut.c_pk_id;
        item.subMenu = [];
        item.ext = shortcut;
        shortMenu.subMenu.push(item);
      } else if (type === 'update') {
        const shortMenu = this.menusData[this.menusData.length - 1];
        const subMenu = shortMenu.subMenu;
        const id = shortcut.c_pk_id;
        for (let i = 0; i < subMenu.length; i++) {
          if (id === subMenu[i].code) {
            subMenu[i].componentName = shortcut.c_comp_name;
            subMenu[i].label = shortcut.c_page_name;
            subMenu[i].ext = shortcut;
            break;
          }
        }
      }
    },
    delMsg(item) {
      const id = item.c_pk_id;
      deleteMsg({
        id
      }).then(res => {
        if (res.success) {
          this.fetchMes();
        }
      });
    },
    /**
     * 加载菜单面包屑
     * @url 跳转的路由地址
     * @menusName 菜单中文名称
     */
    loadFrameBreadcrumb(url, menusName, code) {
      const arr = this.checkMenu(url, menusName, code, this.menusData) || [];
      this.frameBreadcrumb = [
        {
          code: '-1',
          path: '/',
          cName: '首页'
        }
      ];
      Array.prototype.push.apply(this.frameBreadcrumb, arr);
    },
    /**
     * 递归查询菜单
     *
     */
    checkMenu(url, menusName, code, menuArr) {
      const arr = [];
      for (let i = 0, len = menuArr.length; i < len; i++) {
        let toUrl = menuArr[i].sysUrl + menuArr[i].url;
        if (toUrl.includes('.html') && !toUrl.includes('.html#')) {
          toUrl = toUrl.replace('.html', '.html#');
          toUrl.endsWith('#') && (toUrl += '/');
        }
        if (toUrl === url && menuArr[i].label === menusName) {
          arr.push({
            code: code,
            path: '/web/' + stringToBase64(toUrl) + '/' + stringToBase64(menusName) + '/' + code,
            cName: menusName
          });
          return arr;
        } else if (menuArr[i].subMenu.length > 0) {
          const backArr = this.checkMenu(url, menusName, code, menuArr[i].subMenu);
          if (backArr) {
            arr.push({
              id: menuArr[i].code,
              path: '/web/' + stringToBase64(toUrl) + '/' + stringToBase64(menuArr[i].label) + '/' + menuArr[i].code,
              cName: menuArr[i].label
            });
            Array.prototype.push.apply(arr, backArr);
            return arr;
          }
        }
      }
      return false;
    }
  }
};
</script>

<style lang="scss" scoped>
.index-page {
  display: flex;
  flex-direction: column;
  height: 100%;
  .sub-sys-frame {
    position: relative;
    flex: 1;
    z-index: 100;
  }
  .is-show {
    width: 100%;
    flex: 1;
    overflow: auto;
    padding: 10px 20px 10px;
    background: #fff;
    margin: 0;
  }
  .portal-tabs {
    /deep/ .el-tabs__header {
      margin-bottom: 0;
    }
    /deep/ .el-tabs__content {
      height: calc(100% - 46px);
      .el-tab-pane {
        height: 100%;
      }
      .el-tabs__nav-next,
      .el-tabs__nav-prev {
        text-align: center;
        width: 22px;
        height: 29px;
        line-height: 33px;
        z-index: 100;
        background: #fff;
      }
    }
  }
}
.dialog-body-wrap {
  .drag-item {
    display: inline-block;
    padding: 0 12px;
    margin-right: 10px;
    margin-bottom: 10px;
    height: 42px;
    line-height: 42px;
    border: 1px solid #ccc;
    cursor: move;
  }
  .drag-tip {
    padding-bottom: 16px;
    color: #999;
    font-size: 14px;
  }
}

.frame-loading {
  position: relative;
  margin: 20px;
  height: 40px;
  background: #eee;
  &::before {
    content: '';
    position: absolute;
    top: 60px;
    left: 0;
    width: 100%;
    height: 80px;
    background: #eee;
  }
  &::after {
    content: '';
    position: absolute;
    top: 160px;
    left: 0;
    width: 100%;
    height: 80px;
    background: #eee;
  }
}
.frame404 {
  text-align: center;
  font-size: 18px;
  color: #ccc;
  img {
    display: block;
    margin: 0 auto;
    padding-top: 40px;
  }
}
/* /deep/ .sys-copright {
	display: none;
} */
.flex-box {
	z-index: -1 !important
}
.sys-main {
	z-index: -1 !important
}
</style>
